﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class NeedMaterialDetailEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (Request.QueryString["NeedMaterialID"] != null)
                {
                    if (Request.QueryString["NeedMaterialID"].ToString() != null)
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblNeedMaterialID.Text = Request.QueryString["NeedMaterialID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }

                //绑定页面基本数据
                this.BindData();

                ////设置经办人
                //UART.Accounts.Bus.User currentUser = (UART.Accounts.Bus.User)(Session["UserInfo"]);
                //this.lblCurrentUser.Text = currentUser.UserName;
                //this.lblManager.Text = currentUser.TrueName;
            }
        }
        private void BindData()
        {
            //实例化用料单业务处理类与实体类
            var bllNeedHeader =
                 mk.l.Sales_NeedMaterialHeader.ToList();
            Sales_NeedMaterialHeader mNeedHeader =
                bllNeedHeader.Single(h => h.NeedMaterialID == (int.Parse(this.lblNeedMaterialID.Text)));
            if (mNeedHeader != null)
            {
                //设置经办人
                Accounts_Users currentUser =
                        mk.l.Accounts_Users.FirstOrDefault();
                //设置根部门ID
                var bllDept =
                    mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text =
                    bllDept.Single(k => k.ClassID == (int.Parse(currentUser.DepartmentID))).RootID.ToString();
                if (int.Parse(this.lblRootDepartmentID.Text) ==
                    mNeedHeader.RootDepartmentID)
                {
                    //取得订单编号
                    this.lblSalesOrderID.Text =
                        mNeedHeader.SalesOrderID.ToString();
                    var bllOrderHeader =
                       mk.l.Sales_SalesOrderHeader.ToList();
                    //使用业务逻辑对象获取订单信息
                    Sales_SalesOrderHeader mOrderHeader =
                         bllOrderHeader.Single(h => h.SalesOrderID == (mNeedHeader.SalesOrderID));
                    if (mOrderHeader != null)
                    {
                        //先判断是否是本人添加的订单，不能修改别人添加的订单
                        if (mOrderHeader.Designer == currentUser.UserName)
                        {
                            this.BindMaterialCategoryID();
                            this.BindNeedMaterialDetail();
                            this.txtContractAmount.Text = mOrderHeader.ContractAmount.ToString();
                            this.txtBrokerage.Text = mOrderHeader.Brokerage.ToString();
                            this.txtSubTotal.Text = mOrderHeader.SubTotal.ToString();
                            this.txtTotalDue.Text = mOrderHeader.TotalDue.ToString();
                            //如果用料单已经流转，则把两个修改按钮设置为不可见 把关闭按钮设置为可见
                            if (mNeedHeader.StatusSubmit != "1")
                            {
                                this.pnlAdd.Visible = false;
                                this.btnOK.Enabled = false;
                                this.btnOK.Visible = false;
                                this.btnSubmit.Enabled = false;
                                this.btnSubmit.Visible = false;
                                this.myGridView.Columns[5].Visible = false;
                            }
                            else
                            {
                                this.btnOK.Enabled = true;
                                this.btnOK.Visible = true;
                                this.btnSubmit.Enabled = true;
                                this.btnSubmit.Visible = true;
                            }
                        }
                        else
                        {
                            mk.Alert("不能修改他人添加的订单！");
                        }
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("只能操作本店的订单！");
                }
            }
            else
            {
                mk.Alert("参数错误！");
            }
        }
        private void BindMaterialCategoryID()
        {
            var bll = mk.l.Sales_MaterialCategory.ToList();
            var ds = bll.ToList();
            this.rbtnlMaterialCategoryID.DataSource = ds;
            this.rbtnlMaterialCategoryID.DataTextField = "Name";
            this.rbtnlMaterialCategoryID.DataValueField = "MaterialCategoryID";
            this.rbtnlMaterialCategoryID.DataBind();
        }


        /// <summary>
        /// Binds the need material detail.绑定用料单明细
        /// </summary>
        private void BindNeedMaterialDetail()
        {
            var a = mk.l.Sales_NeedMaterialDetail.ToList();
            var b = mk.l.Sales_Material.ToList();
            var ds = from c in a join d in b on c.MaterialID equals d.MaterialID select new { NeedMaterialID = c.NeedMaterialID, DetailID = c.DetailID, SalesOrderID = c.SalesOrderID, ManufacturerID = c.ManufacturerID, MaterialID = c.MaterialID, Quantity = c.Quantity, UnitPrice = c.UnitPrice, Subtotal = c.Subtotal, RealUnitPrice = c.RealUnitPrice, RealSubTotal = c.RealSubTotal, ModifiedDate = c.ModifiedDate, Name = d.Name };
            //a.Join(b,a =>a.MaterialID,b =>b.MaterialID).Where(h => h.NeedMaterialID.ToString() == this.lblNeedMaterialID.Text);
            var t = ds.Where(h => h.NeedMaterialID.ToString() == this.lblNeedMaterialID.Text);
            this.myGridView.DataSource = t.ToList();
            this.myGridView.DataBind();
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                var bllNeedHeader = mk.l.Sales_NeedMaterialHeader.ToList();
                Sales_NeedMaterialHeader mNeedHeader = bllNeedHeader.Single(h => h.NeedMaterialID == (int.Parse(this.lblNeedMaterialID.Text)));
                if (mNeedHeader != null)
                {
                    if (mNeedHeader.StatusSubmit == "1")
                    {
                        var bllOrderHeader = mk.l.Sales_SalesOrderHeader.ToList();
                        Sales_SalesOrderHeader mOrderHeader = bllOrderHeader.Single(h => h.SalesOrderID == (int.Parse(this.lblSalesOrderID.Text)));
                        mOrderHeader.ContractAmount = decimal.Parse(this.txtContractAmount.Text);
                        mOrderHeader.SubTotal = decimal.Parse(this.txtSubTotal.Text);
                        mOrderHeader.TotalDue = decimal.Parse(this.txtTotalDue.Text);
                        mOrderHeader.Brokerage = decimal.Parse(this.txtBrokerage.Text);
                        mOrderHeader.RealIncome = mOrderHeader.TotalDue - mOrderHeader.Brokerage;

                        //修改用料单状态
                        mNeedHeader.StatusSubmit = "2";
                        try
                        {
                            //判断订单的付款状态 如果订单已经为已付全款的状态，则要判断如果应付款大于已付款，则设置为未付全款
                            if (mOrderHeader.StatusPayment == "3")
                            {
                                if (mOrderHeader.PrepaidPayment < mOrderHeader.TotalDue)
                                {
                                    mOrderHeader.StatusPayment = "2";
                                }
                            }
                            mk.l.SubmitChanges();
                            //设置订单的状态
                            mOrderHeader.StatusSubmit = mk.GetStatusSubmit(mOrderHeader.SalesOrderID);
                            //更新订单的订货状态
                            mOrderHeader.StatusPurchaseMaterial = mk.GetStatusPurchaseMaterial(mOrderHeader.SalesOrderID);
                            mk.l.SubmitChanges();
                            //此时再次根据更新后的用料金额和客户实付款计算用料单明细的真正销售价格和合计金额
                            UpdateNeedMaterialDetailRealUnitPriceAndSubTotal();

                            //提交事务
                            //ContextUtil.SetComplete();
                            mk.Alert("用料单明细提交成功！");
                        }
                        catch (Exception ex)
                        {
                            //撤销事务
                           // ContextUtil.SetAbort();
                            mk.Alert("用料单明细修改失败！错误信息：" + ex.Message);
                        }
                    }
                    else
                    {
                        mk.Alert("用料单明细修改失败！此用料单已经提交");
                    }
                }
                else
                {
                    mk.Alert("参数错误！此用料单不存在或已被删除");
                }
            }

        }
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Label lblManufacturerCode = (Label)(e.Row.FindControl("lblManufacturerCode"));
                //UART.BLL.Sales.Manufacturer bllManufacturer = new UART.BLL.Sales.Manufacturer();
                //UART.Model.Sales.Manufacturer mManufacturer = bllManufacturer.GetModel(int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["ManufacturerID"].ToString()));
                //lblManufacturerCode.Text = mManufacturer.ManufacturerCode;
            }
        }
        protected void txtName_TextChanged(object sender, EventArgs e)
        {
            string strMaterialName = mk.InputText(this.txtName.Text, 50);
            var bll = mk.l.Sales_Material.ToList();
            Sales_Material m = bll.Where(h => h.Name.ToString() == (strMaterialName).ToString().Trim()).FirstOrDefault();

            if (m != null)
            {
                this.rbtnlMaterialCategoryID.Items.FindByValue(m.MaterialCategoryID.ToString()).Selected = true;
                //UART.BLL.Sales.Manufacturer bllM = new UART.BLL.Sales.Manufacturer();
                //UART.Model.Sales.Manufacturer mM = bllM.GetModel(m.ManufacturerID);
                //if (mM != null)
                //{
                //    this.txtManufacturerCode.Text = mM.ManufacturerCode;
                //}
                this.txtManufacturerCode.Text = m.ManufacturerCode;
            }
            else
            {
                this.rbtnlMaterialCategoryID.ClearSelection();
                this.txtManufacturerCode.Text = string.Empty;
            }
        }
        protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var bll = mk.l.Sales_NeedMaterialDetail.ToList();
            try
            {
                Sales_NeedMaterialDetail d = bll.Single(h => h.DetailID == int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["DetailID"].ToString()));
                mk.l.Sales_NeedMaterialDetail.DeleteOnSubmit(d);
                mk.l.SubmitChanges();
                this.UpdateSalesOrderInfo();
                //提交事务
                // ContextUtil.SetComplete();
            }
            catch (Exception ex)
            {
                //撤销事务
                //ContextUtil.SetAbort();
                this.lblMsg2.Text = "删除错误！错误信息：" + ex.Message;
            }
            this.BindNeedMaterialDetail();
        }
        protected void btnAddProduct_Click(object sender, EventArgs e)
        {

            var bllNeedHeader = mk.l.Sales_NeedMaterialHeader.ToList();
            int b = int.Parse(this.lblNeedMaterialID.Text);
            Sales_NeedMaterialHeader mNeedHeader = bllNeedHeader.Single(h => h.NeedMaterialID == b);
            if (mNeedHeader != null)
            {
                if (mNeedHeader.StatusSubmit == "1")
                {
                    var bll = mk.l.Sales_NeedMaterialDetail.ToList();
                    Sales_NeedMaterialDetail m = new Sales_NeedMaterialDetail();

                    try
                    {
                        //先根据厂家代码取得厂家ID
                        var bllManufacturerCode = mk.l.Sales_ManufacturerCode.ToList();
                        var bllManufacturer = mk.l.Sales_Manufacturer.ToList();
                        Sales_Manufacturer mManufacturer = bllManufacturer.Single(h => h.ManufacturerID == (bllManufacturerCode.Single(j => j.Code == this.txtManufacturerCode.Text).ManufacturerID));
                        int intMaterialID = 0;
                        //判断材料列表中有无此种材料 如果没有 则添加之
                        string strName = mk.InputText(this.txtName.Text, 50);
                        int intMaterialCategoryID = int.Parse(this.rbtnlMaterialCategoryID.SelectedValue);
                        var bllMaterial = mk.l.Sales_Material.ToList();
                        Sales_Material mMaterial = new Sales_Material();
                        //if (!bllMaterial.Exists(intMaterialCategoryID, mManufacturer.ManufacturerID, strName))
                        if (bllMaterial.Where(h => h.MaterialID == intMaterialCategoryID & h.Name == strName).Count() == 0)
                        {
                            mMaterial.ManufacturerID = mManufacturer.ManufacturerID;
                            mMaterial.MaterialCategoryID = intMaterialCategoryID;
                            mMaterial.Name = strName;
                            mMaterial.ManufacturerCode = mk.InputText(this.txtManufacturerCode.Text, 20);
                            int a = int.Parse(this.lblRootDepartmentID.Text);
                            mMaterial.RootDepartmentID = a;
                            mk.l.Sales_Material.InsertOnSubmit(mMaterial);
                            mk.l.SubmitChanges();
                            intMaterialID = mMaterial.MaterialID;
                        }
                        else
                        {
                            //mMaterial = bllMaterial.GetModel(intMaterialCategoryID, mManufacturer.ManufacturerID, strName);
                            mMaterial = bllMaterial.Single(h => h.MaterialID == intMaterialCategoryID & h.Name == strName);
                            intMaterialID = mMaterial.MaterialID;
                        }

                        m.ModifiedDate = System.DateTime.Now;
                        m.ManufacturerID = mManufacturer.ManufacturerID;
                        m.MaterialID = intMaterialID;
                        m.NeedMaterialID = int.Parse(this.lblNeedMaterialID.Text);
                        m.Quantity = decimal.Parse(this.txtQuantity.Text);
                        m.SalesOrderID = int.Parse(this.lblSalesOrderID.Text);
                        m.UnitPrice = decimal.Parse(this.txtUnitPrice.Text);
                        //计算小计金额
                        m.Subtotal = m.Quantity * m.UnitPrice;
                        //计算实际单价和实际小计金额，也就是实际给公司带来的收入

                        mk.l.Sales_NeedMaterialDetail.InsertOnSubmit(m);
                        mk.l.SubmitChanges();
                        //更新订单概览的相关信息
                        this.UpdateSalesOrderInfo();
                        //绑定材料列表
                        this.BindNeedMaterialDetail();
                        //把输入框设置为空
                        this.txtName.Text = string.Empty;
                        this.txtUnitPrice.Text = string.Empty;
                        this.txtQuantity.Text = string.Empty;
                        this.txtManufacturerCode.Text = string.Empty;
                        //清除选定项
                        this.rbtnlMaterialCategoryID.ClearSelection();
                        //提交事务
                        //   ContextUtil.SetComplete();
                    }
                    catch (Exception ex)
                    {
                        //撤销事务
                        // ContextUtil.SetAbort();
                        this.lblMsg2.Text = "添加错误！错误信息：" + ex.Message;
                    }
                }
                else
                {
                    this.lblMsg2.Text = "添加错误！此用料单已经提交";
                }
            }
            else
            {
                this.lblMsg2.Text = "参数错误！此用料单不存在或已被删除";
            }

        }
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (this.myGridView.Rows.Count > 0)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }
        protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
        {

        }
        private void UpdateSalesOrderInfo()
        {
            //设置订单的客户合同金额和用料合计金额和客户实付金额 只是暂时的
            var bll = mk.l.Sales_SalesOrderHeader.ToList();
            decimal decSubTotal = Convert.ToDecimal(bll.Where(h => h.SalesOrderID == (int.Parse(this.lblSalesOrderID.Text))).Select(k => k.SubTotal).Sum());
            this.txtSubTotal.Text = decSubTotal.ToString("f2");
            //this.txtTotalDue.Text = decSubTotal.ToString("f2");
            Sales_SalesOrderHeader m = bll.Single(h => h.SalesOrderID == (int.Parse(this.lblSalesOrderID.Text)));
            m.SubTotal = decSubTotal;
            //m.TotalDue = decSubTotal;
            m.Brokerage = decimal.Parse(this.txtBrokerage.Text);
            //如果实付金额小于等于设计师佣金 则把设计师佣金设置为0
            if (m.TotalDue <= m.Brokerage)
            {
                m.Brokerage = 0;
                this.txtBrokerage.Text = "0.00";
            }
            m.RealIncome = m.TotalDue - m.Brokerage;

            mk.l.SubmitChanges();
            //更新用料单明细的真实单价和真实小计金额
            UpdateNeedMaterialDetailRealUnitPriceAndSubTotal();
            //      bll.UpdateNeedMaterialDetailRealUnitPriceAndSubTotal(int.Parse(this.lblSalesOrderID.Text));
        }

        private void UpdateNeedMaterialDetailRealUnitPriceAndSubTotal()
        {
            var v = mk.l.Sales_SalesOrderHeader.ToList();
            Sales_SalesOrderHeader j = v.Where(h => h.SalesOrderID == int.Parse(this.lblSalesOrderID.Text)).FirstOrDefault();

            decimal Discount = 1;

            if (j.SubTotal > 0)
            {
                Discount = Convert.ToDecimal(j.TotalDue / j.SubTotal);

            }
            var f = mk.l.Sales_NeedMaterialDetail.ToList();
            var d = f.Where(h => h.SalesOrderID == int.Parse(this.lblSalesOrderID.Text));
            foreach (Sales_NeedMaterialDetail o in d)
            {
                o.RealUnitPrice = o.UnitPrice * Discount;
                o.RealSubTotal = o.Subtotal * Discount;
            }
            mk.l.SubmitChanges();
            // mk.Alert("更新成功");
        }
        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                var bllNeedHeader = mk.l.Sales_NeedMaterialHeader.ToList();
                Sales_NeedMaterialHeader mNeedHeader = bllNeedHeader.Single(h => h.NeedMaterialID == (int.Parse(this.lblNeedMaterialID.Text)));
                if (mNeedHeader != null)
                {
                    if (mNeedHeader.StatusSubmit == "1")
                    {
                        var bll = mk.l.Sales_SalesOrderHeader.ToList();
                        Sales_SalesOrderHeader m = bll.Single(h => h.SalesOrderID == (int.Parse(this.lblSalesOrderID.Text)));
                        m.ContractAmount = decimal.Parse(this.txtContractAmount.Text);
                        m.SubTotal = decimal.Parse(this.txtSubTotal.Text);
                        m.TotalDue = decimal.Parse(this.txtTotalDue.Text);
                        m.Brokerage = decimal.Parse(this.txtBrokerage.Text);
                        m.RealIncome = m.TotalDue - m.Brokerage;
                        try
                        {
                            mk.l.SubmitChanges();
                            //此时再次根据更新后的用料金额和客户实付款计算用料单明细的真正销售价格和合计金额
                            UpdateNeedMaterialDetailRealUnitPriceAndSubTotal();
                            //提交事务
                           // ContextUtil.SetComplete();
                            mk.Alert("用料单明细修改成功！");
                        }
                        catch (Exception ex)
                        {
                            //撤销事务
                           // ContextUtil.SetAbort();
                            mk.Alert("用料单明细修改失败！错误信息：" + ex.Message);
                        }
                    }
                    else
                    {
                        mk.Alert("用料单明细修改失败！此用料单已经提交");
                    }
                }
                else
                {
                    mk.Alert("参数错误！此用料单不存在或已被删除");
                }
            }
        }

        protected void myGridView_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}